package com.xuecheng.manage_media.service;

import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.request.QueryMediaFileRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_media.dao.MediaFileRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MediaFileService {
    @Resource
    private MediaFileRepository mediaFileRepository;

    /**
     * 分页查询视频信息
     *
     * @param page                  当前第几页
     * @param size                  每页显示多少
     * @param queryMediaFileRequest 可以携带参数查询
     * @return 返回数据
     */
    public QueryResponseResult<?> findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        page = page - 1;
        if (page < 0) {
            page = 0;
        }
        if (size > 50) {
            size = 10;
        }
        PageRequest pageRequest = PageRequest.of(page, size);

        MediaFile mediaFile = new MediaFile();
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getFileOriginalName())) {
            mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
        }
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getProcessStatus())) {
            mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
        }
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getTag())) {
            mediaFile.setTag(queryMediaFileRequest.getFileOriginalName());
        }


        ExampleMatcher matching = ExampleMatcher.matching()
                .withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("fileOriginalName",ExampleMatcher.GenericPropertyMatchers.contains());

        Example<MediaFile> example = Example.of(mediaFile,matching);

        Page<MediaFile> mediaFilePage = mediaFileRepository.findAll(example, pageRequest);

        QueryResult<MediaFile> queryResult = new QueryResult<>();
        queryResult.setTotal(mediaFilePage.getTotalElements());
        queryResult.setList(mediaFilePage.getContent());
        return new QueryResponseResult<>(CommonCode.SUCCESS, queryResult);
    }
}
